package com.googlecode.javatools.classparser.types.impl;

import com.googlecode.javatools.classparser.types.ConstantEntry;

public class ConstantEntryDefault implements ConstantEntry
{
	private static final int CONSTANT_UTF8 = 1;

	private byte tag;
	private int nameIndex;
	private int typeIndex;
	private Object value;

	public ConstantEntryDefault(final byte tag, final int nameIndex)
	{
		this(tag, nameIndex, -1);
	}

	public ConstantEntryDefault(final byte tag, final Object value)
	{
		this(tag, -1, -1);
		this.value = value;
	}

	public ConstantEntryDefault(final byte tag, final int nameIndex, final int typeIndex)
	{
		this.tag = tag;
		this.nameIndex = nameIndex;
		this.typeIndex = typeIndex;
		this.value = null;
	}

	public Object value()
	{
		return this.value;
	}

	public byte getTag()
	{
		return this.tag;
	}

	public int getNameIndex()
	{
		return this.nameIndex;
	}

	public int getTypeIndex()
	{
		return this.typeIndex;
	}

	public String toUTF8()
	{
		if (getTag() == CONSTANT_UTF8) { return (String) value(); }

		throw new IllegalStateException("Constant pool entry is not a UTF8 type: ");
	}

	@Override
	public String toString()
	{

		final StringBuffer s = new StringBuffer("");

		s.append("tag: " + getTag());

		if (getNameIndex() > -1)
		{
			s.append(" nameIndex: " + getNameIndex());
		}

		if (getTypeIndex() > -1)
		{
			s.append(" typeIndex: " + getTypeIndex());
		}

		if (value() != null)
		{
			s.append(" value: " + value());
		}

		return s.toString();
	}
}
